﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.IO;
/// <summary>
/// Summary description for clsCommon
/// </summary>
public class clsCommon
{
    public clsCommon()
    {

    }

    public string LimitWord(string value)
    {
        if (value.Length > 500)
            return value.Substring(0, 500) + "...";
        else
            return value;

    }


    public int SearchArrList(ArrayList arr, string value)
    {
        int index = -1;
        for (int i = 0; i < arr.Count; i++)
        {
            if (arr[i].ToString() == value)
            {
                index = i;
                break;
            }
        }
        return index;
    }

    public int SearchDataTable(DataTable dt, string Col, string value)
    {
        int index = -1;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i][Col].ToString() == value)
            {
                index = i;
                break;
            }
        }
        return index;
    }

    public decimal ConvertToDecimal(string value)
    {
        decimal dReturn = 0;
        try
        {
            if (value != "" && value != null)
                dReturn = decimal.Parse(value);
        }
        catch { Exception ex; }
        return dReturn;
    }

    public string ResponsePageFile(string pagefile)
    {
        string strUrl = "";

        if (pagefile != "" && pagefile != null)
            strUrl = "~/" + pagefile;
        else
            strUrl = "~/home.aspx";
        return strUrl;
    }
    public string EncodeUpdID(string encode)
    {
        return encode;
    }
    public string FormatDate(string sDate)
    {
        string sReturn = "";
        try
        {
            sReturn = sDate.ToString().Substring(6, 2) + "/" + sDate.ToString().Substring(4, 2) + "/" + sDate.ToString().Substring(0, 4);
        }
        catch (Exception ex) { }

        return sReturn;
    }
    public string FormatDateTime(string sDate)
    {
        string sReturn = "";
        try
        {
            sReturn = sDate.ToString().Substring(6, 2) + "/" + sDate.ToString().Substring(4, 2) + "/" + sDate.ToString().Substring(0, 4);
            sReturn += "  " + sDate.ToString().Substring(8, 2) + ":" + sDate.ToString().Substring(10, 2) + ":" + sDate.ToString().Substring(12, 2);
        }
        catch (Exception ex) { }

        return sReturn;
    }
    public string FormatDateTimeChina(string sDate)
    {
        string sReturn = "";
        try
        {
            sReturn = sDate.ToString().Substring(6, 2) + "/" + sDate.ToString().Substring(4, 2) + "/" + sDate.ToString().Substring(0, 4);
            sReturn += "  " + sDate.ToString().Substring(8, 2) + ":" + sDate.ToString().Substring(10, 2) + ":" + sDate.ToString().Substring(12, 2);
        }
        catch (Exception ex) { }

        return sReturn;
    }
    public string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }

    public string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }
    public string base64Encode(string data)
    {
        try
        {
            byte[] encData_byte = new byte[data.Length];
            encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
            string encodedData = Convert.ToBase64String(encData_byte);
            return encodedData;
        }
        catch (Exception e)
        {
            throw new Exception("Error in base64Encode" + e.Message);
        }
    }
    public string base64Decode(string data)
    {
        try
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();

            byte[] todecode_byte = Convert.FromBase64String(data);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        catch (Exception e)
        {

        }
        return "error";
    }


    public string Send_AppEmail(string SendFrom, string SendTo, string CC, string Subject, string Body)
    {
        string SMTP = "", sPort = "", UserName = "", Password = "";
        try
        {
            System.Security.Cryptography.RijndaelManaged mobjCryptoService = new System.Security.Cryptography.RijndaelManaged();
            EncrypKey cls = new EncrypKey(mobjCryptoService);

            SMTP = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"].ToString();
            sPort = System.Configuration.ConfigurationManager.AppSettings["Port"].ToString();
            UserName = System.Configuration.ConfigurationSettings.AppSettings["UserName"].ToString();
            Password = cls.Decrypting(System.Configuration.ConfigurationSettings.AppSettings["Password"].ToString(), System.Configuration.ConfigurationManager.AppSettings["EncrypKey"]);



            /***********************/


            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");


            bool result = regex.IsMatch(SendTo);
            if (result == false)
            {

                return "V";
            }
            else
            {
                System.Net.Mail.SmtpClient smtp = new SmtpClient();
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(SendFrom, SendTo, Subject, Body);
                if (CC.Trim() != "")
                {
                    string[] arrCC = CC.Split(';');

                    for (int i = 0; i < arrCC.Length; i++)
                    {
                        if (arrCC[i] != "")
                            msg.Bcc.Add(new MailAddress(arrCC[i]));
                    }
                }

                msg.IsBodyHtml = true;

                smtp.Host = SMTP;//Sử dụng SMTP của gmail
                smtp.Port = int.Parse(sPort);
                NetworkCredential info = new NetworkCredential(UserName, Password);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = info;
                smtp.EnableSsl = true;

                smtp.Send(msg);
                return "Y";

            }
        }
        catch
        {
            return "N";
        }
    }

    public string Send_AppEmail(string SendFrom, string SendTo, string CC, string UrlAttachment, string Subject, string Body)
    {
        string SMTP = "", sPort = "", UserName = "", Password = "";
        try
        {
            System.Security.Cryptography.RijndaelManaged mobjCryptoService = new System.Security.Cryptography.RijndaelManaged();
            EncrypKey cls = new EncrypKey(mobjCryptoService);

            SMTP = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"].ToString();
            sPort = System.Configuration.ConfigurationManager.AppSettings["Port"].ToString();
            UserName = System.Configuration.ConfigurationSettings.AppSettings["UserName"].ToString();
            Password = cls.Decrypting(System.Configuration.ConfigurationSettings.AppSettings["Password"].ToString(), System.Configuration.ConfigurationManager.AppSettings["EncrypKey"]);



            /***********************/


            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");


            bool result = regex.IsMatch(SendTo);
            if (result == false)
            {

                return "V";
            }
            else
            {
                System.Net.Mail.SmtpClient smtp = new SmtpClient();
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(SendFrom, SendTo, Subject, Body);
                if (CC.Trim() != "")
                {
                    string[] arrCC = CC.Split(';');

                    for (int i = 0; i < arrCC.Length; i++)
                    {
                        if (arrCC[i] != "")
                            msg.Bcc.Add(new MailAddress(arrCC[i]));
                    }
                }
                if (UrlAttachment != "")
                {
                    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(UrlAttachment);
                    attach.ContentDisposition.Inline = true;
                    attach.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                    attach.ContentId = "1";
                    attach.ContentType.Name = Path.GetFileName(UrlAttachment);
                    msg.Attachments.Add(attach);
                }

                msg.IsBodyHtml = true;

                smtp.Host = SMTP;//Sử dụng SMTP của gmail
                smtp.Port = int.Parse(sPort);
                NetworkCredential info = new NetworkCredential(UserName, Password);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = info;
                smtp.EnableSsl = true;

                smtp.Send(msg);
                return "Y";

            }
        }
        catch
        {
            return "N";
        }
    }

    #region Old
    /*public string Send_Email1(string SendFrom, string SendTo, string CC, string Subject, string Body)
    {
        try
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");


            bool result = regex.IsMatch(SendTo);
            if (result == false)
            {

                return "V";
            }
            else
            {
                System.Net.Mail.SmtpClient smtp = new SmtpClient();
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.From = new MailAddress(SendFrom);
                msg.To.Add(SendTo);
                if (CC != "")
                {
                    string[] arrCC = CC.Split(';');
                    for (int i = 0; i < arrCC.Length; i++)
                    {
                        if (arrCC[i] != "")
                            msg.Bcc.Add(new MailAddress(arrCC[i]));
                    }
                }
                msg.Subject = Subject;
                msg.Body = Body;
                msg.IsBodyHtml = true;
                smtp.Host = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"].ToString();//Sử dụng SMTP của gmail

               

                smtp.Send(msg);
                return "Y";

            }
        }
        catch
        {
            return "N";
        }
    }
    */
    /*  public string DecodeUpdID(string EncodeStr)
     {
         string ReturnStr, FactStr = "";
         int i, d, h;
         string da, ha;
         int[] A1 = { 3, 7, 8, 1, 12, 3, 9, 23, 11, 6 };
         int startIndex, factIndex;
         string OrgUpd_id = "";
         string[] SplitArray;

         d = DateTime.Today.Day;
         h = DateTime.Now.Hour;

         //kiem tra it nhat la 3 ky tu
         for (i = 1; i <= EncodeStr.Length; i++)
         {
             if ((i % 4) != 0)
             {
                 FactStr = FactStr + EncodeStr.Substring(i - 1, 1);
             }
         }

         //Cac chi so
         startIndex = ((d + h) * 3) % 10;

         for (i = 0; i < FactStr.Length; i++)
         {
             //Cac chi so thuc te
             factIndex = (startIndex + i) % 10;

             //Cong don
             OrgUpd_id = OrgUpd_id + (char)((int)FactStr.Substring(i, 1).ToCharArray()[0] - A1[factIndex]);
         }

         //Lay ngay gio su dung
         SplitArray = OrgUpd_id.Split(':');

         if (SplitArray.Length != 3)
         {
             ReturnStr = "There are not pass.";
             return ReturnStr;
         }

         da = SplitArray[0];
         ha = SplitArray[1];

         if ((Convert.ToInt16(da) != d) || (Convert.ToInt16(ha) != h))
         {
             ReturnStr = "There are not pass1.";
             return ReturnStr;
         }

         ReturnStr = SplitArray[2];

         return ReturnStr;

     }

     public string EncodeUpdID(string upd_id)
     {

         int[] A1 = { 3, 7, 8, 1, 12, 3, 9, 23, 11, 6 };
         int i, d, h, startIndex, factIndex;
         string NetUpd_id, OrgUpd_id;

         d = DateTime.Today.Day;
         h = DateTime.Now.Hour;

         //Lay ngay va gio
         OrgUpd_id = d + ":" + h + ":" + upd_id;
         NetUpd_id = "";


         //lay cac chi so
         startIndex = ((d + h) * 3) % 10;

         for (i = 0; i < OrgUpd_id.Length; i++)
         {
             //nhieu hon 3 ky tu
             if (((i % 3) == 0) && (i > 0))
             {
                 NetUpd_id = NetUpd_id + (char)(65 + i);
             }

             //Lay chi so
             factIndex = (startIndex + i) % 10;

             //Cong don
             NetUpd_id = NetUpd_id + (char)((int)OrgUpd_id.Substring(i, 1).ToCharArray()[0] + A1[factIndex]);
         }

         return NetUpd_id;
     }*/
    #endregion




}
